<template>
  <div>
    <el-card class="card" :body-style="{ backgroundColor: '#E1F5FE' }" style="width: 1351px; height: 585px;">
      <div style="margin-left: 520px; font-size: 25px; margin-top: 20px">个人中心</div>
      <div style="margin-left: 300px; margin-top: 20px">
        <el-form :model="rowData"  ref="ruleFormRef"   :rules="rules" >
          <el-form-item  label="姓名" :label-width="formLabelWidth" :style="{ width: inputWidth }" prop="name">
            <el-input  v-model="rowData.name" autocomplete="off" />
          </el-form-item>
          <el-form-item label="性别" :label-width="formLabelWidth" prop="gender">
            <el-select v-model="rowData.gender" placeholder="请选择性别"  >
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </el-select>
          </el-form-item>
          <el-form-item label="年龄" :label-width="formLabelWidth" :style="{ width: inputWidth }" prop="age"  >
            <el-input  v-model.number="rowData.age" autocomplete="off" />
          </el-form-item>
          <el-form-item label="qq号" :label-width="formLabelWidth" :style="{ width: inputWidth }" prop="qq">
            <el-input   v-model="rowData.qq" autocomplete="off" />
          </el-form-item>
          <el-form-item label="地址" class="custom-input" :label-width="formLabelWidth" :style="{ width: inputWidth }" prop="address">
            <el-input   v-model="rowData.address" autocomplete="off" />
          </el-form-item>
          <el-form-item label="生日" :label-width="formLabelWidth" prop="birthday">
            <el-date-picker v-model="rowData.birthday" type="date" placeholder="选择日期"
                            :value-format="'YYYY-MM-DD'"/>
          </el-form-item>
          <el-form-item label="头像" :label-width="formLabelWidth" :style="{ width: inputWidth }" >
            <el-upload
                class="avatar-uploader"
                action="http://8.137.113.138:88/File/upImg"
                :show-file-list="false"
                :on-success="handleSuccess"
                :before-upload="beforeAvatarUpload"
                accept=".jpg, .png"
            >
              <img v-if="rowData.img" :src="rowData.img" class="avatar" style="width: 300px; height: 130px"/>
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          </el-form>
<!--        <template #footer>-->
<!--      <span class="dialog-footer">-->
        <div style="margin-left: 80px" >
          <span>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          确定上传信息
        </el-button>
          </span>
          <span style="margin-left: 90px">
          <el-button type="success" @click="ChangePassword">
          点击修改密码
        </el-button>
          </span>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref,onMounted} from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import {ElMessage, ElMessageBox, UploadProps} from 'element-plus'
import userApi from "../../apis/user.js";
import { useRouter } from 'vue-router'
const router = useRouter();
onMounted(()=>{
  GetDetailInformation();
})
const rowData = ref({
  name: '',
  gender:'',
  img:'',
  qq:'',
  address:'',
  age:'',
  birthday:'',
})

const  inputWidth= ref('500px');
const formLabelWidth=ref('70px')
const imageUrl = ref('')
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}
const handleSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  console.log(response)
  rowData.value.img=response;
}

//校验表单的数据
const ruleFormRef = ref<FormInstance>()
//校验年龄
const checkAge = (rule: any, value: any, callback: any) => {
  console.log(rule)
  if (!value) {
    return callback(new Error('请输入您的年龄'))
  }
  if (!Number.isInteger(value)) {
    callback(new Error('请输入数字'))
  } else {
    if (value > 100) {
      callback(new Error('年龄不许大于100岁'))
    }
    else if (value <2) {
      callback(new Error('年龄不许小于2岁'))
    } else {
      callback()
    }
  }
}
//校验姓名
const checkName = (rule: any, value: any, callback: any) => {
  //定义中文正则表达式，长度只能为2,3,或者4
  const chineseNameRegex = /^[\u4e00-\u9fa5]{2,4}$/;
  if (value === '') {
    callback(new Error('请输入您的姓名'))
  }else if(!chineseNameRegex.test(value)){
    callback(new Error('请输入2到4个汉字的中文姓名'))
  }else{
    callback();
  }
}
const checkGender = (rule: any, value: any, callback: any) => {
  if (value ==='男' || value=='女') {
    callback()
  }else{
    callback(new Error('请选择您的性别'));
  }
}
//检验输入的qq号码是否正确
const checkNumber = (rule: any, value: any, callback: any) => {
  const  check = /^[1-9]\d{9}$/
  if (value === '') {
    callback(new Error('请输入您的qq号码'))
  }else if(!check.test(value)){
    callback(new Error('请输入只包含数字的10位qq'))
  }else{
    callback();
  }
}
//校验收货地址
const checkAddress = (rule: any, value: any, callback: any) => {
  //定义中文正则表达式，长度只能为2,3,或者4
  const  check =  /^[\u0391-\uFFE5]+$/
  if (value === '') {
    callback(new Error('请输入您的地址'))
  }else if(!check.test(value)){
    callback(new Error('请输入中文地址号'))
  }else{
    callback();
  }
}
//检验生日是否填写

const checkBirthday= (rule: any, value: any, callback: any) => {
  if (value ==='') {
    callback(new Error('请选择生日日期'))
  }else{
    callback();
  }
}
const rules = ref<FormRules<typeof rowData>>({
  name: [{ validator: checkName, trigger: 'blur',required:true}],
  gender: [{ validator: checkGender, trigger: 'blur',required:true }],
  age: [{ validator: checkAge, trigger: 'blur',required:true}],
  qq: [{ validator: checkNumber, trigger: 'blur',required:true }],
  address: [{ validator: checkAddress, trigger: 'blur',required:true }],
  birthday: [{ validator: checkBirthday, trigger: 'blur',required:true }],
})
const submitForm = (formEl: FormInstance | undefined) => {
  console.log(formEl)
  //如果图片没有上传的话
  if(rowData.value.img===''){
    ElMessage({
      message: '请上传图片',
      type: 'warning',
    })
    return
  }
  //如果表格没有填写的话
  if (!formEl) {
    ElMessage({
      message: '请填写完整表格信息',
      type: 'warning',
    })
    return
  }
  formEl.validate((valid) => {
    if (valid) {
      ifAddUser();
    } else {
      return false
    }
  })
}
const backData =ref();
const GetDetailInformation = () => {
  userApi.GetInformation().then(res=>{
    backData.value=res.data;
    if(res.data==null){
      return
    }
    console.log(backData.value)
    rowData.value.img=backData.value.img;
    rowData.value.age=backData.value.age;
    rowData.value.qq =backData.value.qq;
    rowData.value.gender = backData.value.gender;
    rowData.value.address =backData.value.address;
    rowData.value.birthday =backData.value.birthday;
    rowData.value.name =backData.value.name;
  })
}
const ifAddUser = () => {
  console.log("确定要上传了吗")
  ElMessageBox.confirm(
      '个人信息上传之后不可由自己修改,是否继续,若要修改请联系管理员',
      'Warning',
      {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning',
      }
  )
      .then(() => {
        userApi.CheckExist().then(res=>{
          console.log(res)
          console.log('这个是是否存在的信息')
          console.log(res.status);
          if(res.status=='true'){
            ElMessage.warning({
              message: '已有信息禁止重复上传！',
              duration: 1500, // 设置显示时间为 1.5 秒
            });
            console.log("确实有的")
            return
          }
          else{
            userApi.PostInformation(rowData.value).then(res=>{
              console.log(res.data)
              console.log("上传了哈哈哈");
              ElMessage.success({
                message: '上传信息成功',
                duration: 1500, // 设置显示时间为 1.5 秒
              });
            })
          }
        })
        userApi.GetInformation().then(res=>{
          backData.value=res.data;
          console.log(res.data)
          console.log(backData.value)
          rowData.value.img=backData.value.img;
          rowData.value.age=backData.value.age;
          rowData.value.qq =backData.value.qq;
          rowData.value.gender = backData.value.gender;
          rowData.value.address =backData.value.address;
          rowData.value.birthday =backData.value.birthday;
          rowData.value.name =backData.value.name;
          console.log('666')
          console.log('这个是那个获取单个人的哪个信息')
        })
        // location.reload()
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: 'canceled',
        })
      })
}
const ChangePassword = () => {
  router.push({name:"Password"})
  console.log("我要修改密码了")
}
</script>

<style>
.card {
  background-color: gray;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
}
</style>
